<template>
  <div class="app-container">
    <el-form
      :inline="true"
      :model="queryParams"
      label-width="80px"
      ref="queryForm"
      size="small"
      v-show="showSearch"
    >
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          @keyup.enter.native="handleQuery"
          clearable
          placeholder="请输入合同名称"
          v-model="queryParams.contractName"
        />
      </el-form-item>

      <el-form-item label="审核状态" prop="auditState">
        <el-select
          clearable
          placeholder="请选择审核状态"
          v-model="queryParams.auditState"
        >
          <el-option
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            v-for="dict in dict.type.flow_contract_status"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="录入时间">
        <el-date-picker
          end-placeholder="结束日期"
          range-separator="-"
          start-placeholder="开始日期"
          style="width: 240px"
          type="daterange"
          v-model="daterangeInputTime"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          @click="handleQuery"
          icon="el-icon-search"
          size="mini"
          type="primary"
        >搜索
        </el-button
        >
        <el-button @click="resetQuery" icon="el-icon-refresh" size="mini"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          @click="handleAdd"
          icon="el-icon-plus"
          plain
          size="mini"
          type="primary"
          v-hasPermi="['team:contract:add']"
        >新增
        </el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table :data="contractList" v-loading="loading">
      <el-table-column align="center" label="序号" prop="id"/>
      <el-table-column
        align="center"
        label="客户"
        prop="customerName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="合同名称"
        prop="contractName"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="合同编码" prop="contractCode"/>
      <el-table-column
        align="center"
        label="合同金额(单位: 万元)"
        prop="amounts"
        width="180px"
      />

      <el-table-column align="center" label="合同开始日期" prop="startDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同结束日期" prop="endDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="电子附件" prop="appendix">
        <template slot-scope="scope">
          <!--<el-button
            @click="downloadFile(scope.row)"
            icon="el-icon-download"
            size="mini"
            type="text">下载
          </el-button>-->
          <!--<a @click="downloadFile(scope.row)">下载</a>-->
          <a :href="scope.row.appendix">下载</a>
        </template>
      </el-table-column>

      <el-table-column align="center" label="录入人" prop="inputUserName"/>

      <el-table-column
        align="center"
        label="录入时间"
        prop="inputTime"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.inputTime, '{y}-{m}-{d} {h}:{i}:{s}')
          }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="审核状态" prop="auditState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.flow_contract_status"
            :value="scope.row.auditState"
          />
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否盖章" prop="affixSealState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.flow_contract_affixsealstate"
            :value="scope.row.affixSealState"
          />
        </template>
      </el-table-column>

      <el-table-column align="center" label="是否作废" prop="nullifyState">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.flow_contract_nullifystate"
            :value="scope.row.nullifyState"
          />
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            @click="handleUpdate(scope.row)"
            icon="el-icon-edit"
            size="mini"
            type="text"
            v-hasPermi="['team:contract:edit']"
            v-if="scope.row.auditState === -1 && scope.row.nullifyState !== -1">编辑
          </el-button>

          <el-button
            @click="handleDelete(scope.row)"
            icon="el-icon-edit"
            size="mini"
            type="text"
            v-hasPermi="['team:contract:remove']"
            v-if="
              !(
                (scope.row.auditState === 1 &&
                  scope.row.affixSealState === 1) ||
                scope.row.nullifyState === -1
              )
            "
          >作废
          </el-button
          >

          <el-button
            @click="handleAuditPassed(scope.row)"
            icon="el-icon-edit"
            size="mini"
            type="text"
            v-if="scope.row.auditState === 0 && scope.row.nullifyState !== -1"
          >审核通过
          </el-button
          >

          <el-button
            @click="handleAuditNoPassed(scope.row)"
            icon="el-icon-edit"
            size="mini"
            type="text"
            v-if="scope.row.auditState === 0 && scope.row.nullifyState !== -1"
          >审核不通过
          </el-button
          >

          <el-button
            @click="handleAffixSealState(scope.row)"
            icon="el-icon-edit"
            size="mini"
            type="text"
            v-if="
              scope.row.auditState === 1 &&
              scope.row.nullifyState !== -1 &&
              scope.row.affixSealState === 0
            "
          >确认盖章
          </el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
      v-show="total > 0"
    />

    <!-- 添加或修改合同信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="60%">
      <el-form :model="form" :rules="rules" label-width="80px" ref="form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-select v-model="form.customerId">
                <el-option
                  :key="u.id"
                  :label="u.customerName"
                  :value="u.id"
                  v-for="u in users"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input
                placeholder="请输入合同名称"
                v-model="form.contractName"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="合同编码" prop="contractCode">
              <el-input
                placeholder="请输入合同编码"
                v-model="form.contractCode"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="合同金额" prop="amounts">
              <el-input
                placeholder="请输入合同金额"
                type="number"
                v-model="form.amounts"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                clearable
                placeholder="请选择合同生效开始时间"
                type="date"
                v-model="form.startDate"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                clearable
                placeholder="请选择合同生效结束时间"
                type="date"
                v-model="form.endDate"
                value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">

            <el-form-item label="附件" prop="appendix">
              <file-upload v-model="form.appendix"/>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="submitForm" type="primary">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addContract,
    changeAffixSealState,
    changeAuditStatus,
    delContract,
    downloadFileByMinioUrl,
    getContract,
    listContract,
    updateContract
  } from '../../../api/team/contract'
  import { customerteamAll } from '../../../api/team/customerteam'

  export default {
    name: 'Contract',
    dicts: [
      'flow_contract_status',
      'flow_contract_affixsealstate',
      'flow_contract_nullifystate'
    ],
    data() {
      var checkContractName = (rule, contractName, callback) => {
        if (!contractName) {
          return callback(new Error('合同名称必填'))
        }
        if (contractName && contractName.trim().length > 100) {
          return callback(new Error('合同名称不能超过100个字'))
        }
        return callback()
      }

      var checkCcontractCode = (rule, ccontractCode, callback) => {
        if (!ccontractCode) {
          return callback(new Error('合同编码必填'))
        }
        if (ccontractCode && ccontractCode.trim().length > 50) {
          return callback(new Error('合同名称不能超过50个字'))
        }
        return callback()
      }

      var checkAamounts = (rule, amounts, callback) => {
        if (!amounts) {
          return callback(new Error('合同金额必填'))
        }
        // (amounts + "").substring((amounts + "").indexOf('.'), (amounts + "").length).length > 3
        if (amounts < 0) {
          return callback(new Error('定金必须大于0'))
        } else if (amounts && (amounts + '').indexOf('.') === -1) {
          return (this.form.amounts = parseFloat(Number(amounts) + 0.01))
        } else if (
          amounts &&
          (amounts + '').substring(
            (amounts + '').indexOf('.'),
            (amounts + '').length
          ).length > 3
        ) {
          return callback(new Error('必须保留两位小数'))
        }

        return callback()
      }
      return {
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 合同信息表格数据
        contractList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 附件时间范围
        daterangeStartDate: [],
        // 附件时间范围
        daterangeInputTime: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          contractName: null,
          auditState: null,
          inputTime: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          contractName: [
            {
              required: true,
              trigger: 'blur',
              validator: checkContractName
            }
          ],
          contractCode: [
            {
              required: true,
              trigger: 'blur',
              validator: checkCcontractCode
            }
          ],
          amounts: [
            {
              required: true,
              trigger: 'blur',
              validator: checkAamounts
            }
          ],
          startDate: [
            { required: true, trigger: 'blur', message: '请选择合同开始时间' }
          ],
          endDate: [
            { required: true, trigger: 'blur', message: '请选择合同结束时间' }
          ],
          appendix: [
            { required: true, trigger: 'blur', message: '请选择要上传的文件' }
          ]
        },
        users: []
      }
    },
    created() {
      this.getList()

      // 查询所有用户信息
      customerteamAll().then((res) => {
        this.users = res.data
      })
    },
    methods: {
      /** 查询合同信息列表 */
      getList() {
        this.loading = true
        this.queryParams.params = {}
        if (null != this.daterangeStartDate && '' !== this.daterangeStartDate) {
          this.queryParams.params['beginStartDate'] = this.daterangeStartDate[0]
          this.queryParams.params['endStartDate'] = this.daterangeStartDate[1]
        }
        if (null != this.daterangeInputTime && '' !== this.daterangeInputTime) {
          this.queryParams.params['beginInputTime'] = this.daterangeInputTime[0]
          this.queryParams.params['endInputTime'] = this.daterangeInputTime[1]
        }
        listContract(this.queryParams).then((response) => {
          this.contractList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          customerId: null,
          contractName: null,
          contractCode: null,
          amounts: null,
          startDate: null,
          endDate: null,
          appendix: null,
          affixSealState: null,
          auditState: null,
          nullifyState: null,
          inputUser: null,
          inputTime: null
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeStartDate = []
        this.daterangeInputTime = []
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = '添加合同信息'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id
        getContract(id).then((response) => {
          this.form = response.data
          this.open = true
          this.title = '修改合同信息'
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              updateContract(this.form).then((response) => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addContract(this.form).then((response) => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }).catch(res => {})
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id
        this.$modal
          .confirm('确认作废合同信息编号为"' + ids + '"的数据项？')
          .then(function() {
            return delContract(ids)
          })
          .then(() => {
            this.getList()
            this.$modal.msgSuccess('作废成功')
          })
          .catch(() => {
          })
      },
      /** 审核通过 */
      handleAuditPassed(row) {
        const auditStatus = true
        const id = row.id

        this.$modal
          .confirm('确认审核通过合同信息编号为"' + id + '"的数据项？')
          .then(function() {
            return changeAuditStatus(id, auditStatus)
          })
          .then((res) => {
            this.getList()
            this.$modal.msgSuccess('审核通过成功')
          })
          .catch((res) => {
          })
      },
      /** 审核不通过 */
      handleAuditNoPassed(row) {
        const auditStatus = false
        const id = row.id
        this.$modal
          .confirm('确认审核不通过合同信息编号为"' + id + '"的数据项？')
          .then(function() {
            return changeAuditStatus(id, auditStatus)
          })
          .then(() => {
            this.getList()
            this.$modal.msgSuccess('审核通过成功')
          })
          .catch(() => {
          })
      },
      /** 盖章 */
      handleAffixSealState(row) {
        const id = row.id
        this.$modal
          .confirm('确认盖章合同信息编号为"' + id + '"的数据项？')
          .then(function() {
            return changeAffixSealState(id)
          })
          .then(() => {
            this.getList()
            this.$modal.msgSuccess('盖章通过成功')
          })
          .catch(() => {
          })
      },
      /** 下载文件 */
      downloadFile(row) {

        const id = row.id
        this.$modal
          .confirm('确认下载合同信息编号为"' + row.id + '"的电子附件？')
          .then(function() {
            return downloadFileByMinioUrl(id)
          })
          .then(() => {
            this.getList()
            this.$modal.msgSuccess('下载成功')
          })
          .catch(() => {
          })
      }
    }
  }
</script>
